$(document).ready(function(){

	$(document).ajaxStart(function(){
		 $.blockUI({message: '<h1>Calculating...</h1>'});
	});

	$(document).ajaxStop(function(){
		 $.unblockUI();
	});


	$('.minus, .pluss').live('click',function(e){ // "-" or "+" CLICKED -> change value -> trigger input CHANGED event
		e.preventDefault();

		var input = $(this).parent('.qty').find('.qtyinput');
		var val = parseInt(input.val());
		var incdec = $(this).hasClass('minus') ? -1 : 1;

		if(val + incdec <= 0) return false;
		if(val + incdec > input.attr('alt')){
			alert($('#notinstock').text());
			return false;
		}
		input.val(val + incdec);
		input.trigger('change');

		return true;
	});

//	$('.qtyinput').live('keypress',function(e){
//		var code = (e.keyCode ? e.keyCode : e.which);
//
//		if( isUnsignedInteger(String.fromCharCode(code)) || code == 37 || code == 39 || code == 8){
//			return true;
//		}
//
//		return false;
//
//	}).live('keyup',function(e){
//		var code = (e.keyCode ? e.keyCode : e.which);
//
//		if( isUnsignedInteger(String.fromCharCode(code))  || code == 8){
//			$(this).trigger('change');
//		}
//
//	});

	// CHANGED event handler
	$('.qtyinput').live('change',function(e){ // send request, replace HTML content
		var form = $(this).parents('form');
		if (this.value != this.lastValue) {
			var q = this.value;

			//set loader

			// Stop previous ajax-request
			if (this.timer) {
				clearTimeout(this.timer);
			}
			// Start a new ajax-request in X ms
			this.timer = setTimeout(function () {
				form.trigger('changed');
			}, 1000);

			this.lastValue = this.value;
		}
		
	});

	$('#basket_list_form').live('changed', function(){
		var form = $(this);
		var link = form.attr('action');
		$.post(link, form.serialize() ,function(data){
			$('#basketList').html(data);
		});
	});


	// helper function
	function isUnsignedInteger(s) {
		  return (s.toString().search(/^[0-9]+$/) == 0);
	}
});